package com.ganlinux.pangoo.dao.model;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.sql.SQLException;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.ganlinux.pangoo.dao.basemodel.BaseUser;
import com.ganlinux.pangoo.entity.mobsms.RspMobSMS;
import com.ganlinux.pangoo.entity.request.ReqLogin;
import com.ganlinux.pangoo.entity.response.RspLoginData;
import com.ganlinux.pangoo.entity.response.RspUserInfoData;
import com.ganlinux.pangoo.entity.response.base.RspBase;
import com.ganlinux.pangoo.tools.UUIDGenerator;
import com.ganlinux.pangoo.tools.Utils;
import com.jfinal.json.JFinalJson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class User extends BaseUser<User> {
	public static final User dao = new User();
	public boolean checkAccess(String pin,String tocken) {
		User users = findFirst("select * from user where pin = '" + pin + "' and tocken = '"+tocken+"'");
		if (users == null) {
			return false;
		}
		return true;
	}
	public RspBase login(ReqLogin reqLogin) {
		final String phone = reqLogin.getPhone();
		final String code = reqLogin.getCode();
		RspBase rspLogin = new RspBase();

		String paramsString = "appkey=148c5579a1130&amp;phone="+phone+"&amp;zone=86&amp;&amp;code="+code;
		String userPin = null;
//		if (requestData("https://webapi.sms.mob.com/sms/verify",paramsString).equals("succ")) {
		if (true) {

			final User users = findFirst("select * from user where phone = '"+phone+"'");


			//找到phone的用户
			if (users != null) {//有这个用户 更新
				userPin = users.getPin();
			}else {//没有 则创建新的用户
				String pinStr1;
				final User user = new User();
				boolean succeed = Db.tx(new IAtom(){
					public boolean run() throws SQLException {
						User users;
						String pinStr;
						do {
							pinStr = UUIDGenerator.getUUIDForLengh(10);
							users = Db.queryFirst("select * from user where pin = '"+pinStr+"'");
						}while (users != null);
						user.setCode(code);
						user.setName("");
						user.setPhone(phone);
						user.setTocken("");
						user.setLastlogin("");
						user.setWeixinid("");
						user.setPin(pinStr);
						//						int count = Db.update("insert into user set phone = ? and code= ?",phone,code);
						return user.save();
					}});
				if (succeed){
					userPin = user.getPin();
				}else{
					rspLogin.setStatus(1);
					rspLogin.setMessage("失败");
					return rspLogin;
				}
			}
		}else{
			rspLogin.setStatus(1);
			rspLogin.setMessage("失败");
			return rspLogin;
		}

		//找到pin
		final User users = User.dao.findFirst("select * from user where pin = '"+userPin+"'");

		if (users != null) {
			rspLogin.setStatus(0);
			rspLogin.setMessage("成功");
			RspLoginData rspLoginData = new RspLoginData();
			if (users.getTocken() == null||users.getTocken().equals("")) {
				final String token = Utils.getUUID();
				boolean succeed = Db.tx(new IAtom(){
					public boolean run() throws SQLException {
						int count = Db.update("update user set tocken = ? where pin = ?", token, users.getPin());
						return count == 1;
					}});
				rspLoginData.setPin(users.getPin());
			}else {
				rspLoginData.setPin(users.getPin());
			}
			rspLoginData.setToken(users.getTocken());

			rspLoginData.setPhone(users.getPhone());
			rspLogin.setData(rspLoginData);

		}else {
			rspLogin.setStatus(1);
			rspLogin.setMessage("失败");
		}
		return rspLogin;
	}
	public RspUserInfoData getUserInfo(String pin) {

		User users = findFirst("select * from user where pin = '"+pin+"'");
		RspUserInfoData rspUserInfoData = new RspUserInfoData();

		if (users != null) {
			rspUserInfoData.setName(users.getName());
			rspUserInfoData.setPhone(users.getPhone());
			rspUserInfoData.setWeixinid(users.getWeixinid());
			rspUserInfoData.setLastlogin(users.getLastlogin());

			/*Long footPrintNum = Db.queryLong("select count(distinct footprintid) from user_footmark_list where pin = '"+pin+"'");
			Long countryNum = Db.queryLong("select count(distinct countryid) from user_footmark_list where pin = '"+pin+"'");
			Long provinceNum = Db.queryLong("select count(distinct provinceid) from user_footmark_list where pin = '"+pin+"'");
			Long cityNum = Db.queryLong("select count(distinct cityid) from user_footmark_list where pin = '"+pin+"'");
			Long districtNum = Db.queryLong("select count(distinct districtid) from user_footmark_list where pin = '"+pin+"'");
			rspUserInfoData.setFootPrintNum(footPrintNum.intValue());
			rspUserInfoData.setCountryNum(countryNum.intValue());
			rspUserInfoData.setProvinceNum(provinceNum.intValue());
			rspUserInfoData.setCityNum(cityNum.intValue());
			rspUserInfoData.setDistrictNum(districtNum.intValue());*/

		}else {
			rspUserInfoData = null;
		}


		return rspUserInfoData;
	}
	public boolean verifyCode(final String phone, final String code) {

		List<User> users = find("select * from user where phone = '"+phone+"'");

		if (users != null) {
			if (users.size() == 1) {
				final User user = users.get(0);
				boolean succeed = Db.tx(new IAtom(){
					public boolean run() throws SQLException {
						int count = Db.update("update user set code = ? where pin = ?", code, user.getPin());
						return count == 1;
					}});


			}
		}else {
			boolean succeed = Db.tx(new IAtom(){
				public boolean run() throws SQLException {
					int count = Db.update("insert into user set phone = ? and code= ?",phone,code);
					return count == 1;
				}});
		}


		return true;
	}



	/**
	 * 发起https 请求
	 * @param address
	 * @param params
	 * @return
	 */
	public  static String requestData(String address ,String params){

		HttpURLConnection conn = null;
		try {
			// Create a trust manager that does not validate certificate chains
			TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
				public X509Certificate[] getAcceptedIssuers(){return null;}
				public void checkClientTrusted(X509Certificate[] certs, String authType){}
				public void checkServerTrusted(X509Certificate[] certs, String authType){}
			}};

			// Install the all-trusting trust manager
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new SecureRandom());

			//ip host verify
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return urlHostName.equals(session.getPeerHost());
				}
			};

			//set ip host verify
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

			URL url = new URL(address);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");// POST
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(3000);
			// set params ;post params 
			if (params!=null) {
				conn.setDoOutput(true);
				DataOutputStream out = new DataOutputStream(conn.getOutputStream());
				out.write(params.getBytes("UTF-8"));
				out.flush();
				out.close();
			}
			conn.connect();
			//get result 
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//				JFinalJson gson = new Gson();
				String result = parsRtn(conn.getInputStream());
				//            	String result = "succ";
				RspMobSMS rspMobSMS = JFinalJson.getJson().parse(result, RspMobSMS.class);
				if (rspMobSMS.getStatus().equals("200") ) {
					return "succ";
				}
			} else {
				System.out.println(conn.getResponseCode() + " "+ conn.getResponseMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null)
				conn.disconnect();
		}
		return "erro";
	}
	/**
	 * 获取返回数据
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private static  String parsRtn(InputStream is) throws IOException{

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuffer buffer = new StringBuffer();
		String line = null;
		boolean first = true;
		while ((line = reader.readLine()) != null) {
			if(first){
				first = false;
			}else{
				buffer.append("\n");
			}
			buffer.append(line);
		}
		return buffer.toString();
	}


}
